/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: SqlController.java</p>
 *
 * @author zz
 * @date 2024/2/7
 * @version 1.0
 * History:
 * v1.0.0 2024/2/7 Create
 */
package com.sqlweb.sqlweb.controller;

import com.sqlweb.sqlweb.base.Result;
import com.sqlweb.sqlweb.base.ResultCode;
import com.sqlweb.sqlweb.entity.ExecuteSql;
import com.sqlweb.sqlweb.mapper.SqlExecuteLogMapper;
import com.sqlweb.sqlweb.service.DataSourceService;
import com.sqlweb.sqlweb.service.SqlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>Title: SqlController</p>
 * <p>Description: </p>
 *
 * @author zz
 */
@Slf4j
@RestController
@RequestMapping("/sql")
@CrossOrigin(origins = "*")
public class SqlController {
    @Autowired
    SqlExecuteLogMapper sqlExecuteLogMapper;
    @Autowired
    private DataSourceService dataSourceService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    SqlService sqlService;

    @PostMapping("/executeSql")
    public Result executeSql(@RequestBody ExecuteSql executeSql) {
        Object resultData = sqlService.executeSql(executeSql);
        // 返回统一的结果
        return new Result(ResultCode.SUCCESS, resultData);
    }


    @PostMapping("/list")
    public Result listSqlLogs() {
        List<ExecuteSql> executeSqls = sqlExecuteLogMapper.selectAll();
        return new Result(ResultCode.SUCCESS, executeSqls);
    }

    @GetMapping("/viewResult/{id}")
    public ResponseEntity<String> viewResult(@PathVariable("id") Long id) {
        try {
            ExecuteSql executeSql = sqlExecuteLogMapper.selectById(id);
            if (executeSql != null && executeSql.getResultFile() != null) {
                String content = new String(Files.readAllBytes(Paths.get(executeSql.getResultFile())));
                return ResponseEntity.ok(content);
            }
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("文件未找到或无结果");
        } catch (Exception e) {
            log.error("查看失败:" + e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("读取文件时出错");
        }
    }

    @PostMapping("/removeSqlHis")
    public Result removeSqlHis(@RequestBody ExecuteSql executeSql) {
        sqlService.removeSqlHis(executeSql);
        return new Result(ResultCode.SUCCESS, "删除成功");
    }


}
